const api = require('../../utils/api.js');
const app = getApp();

Page({
  data: {
    switch_tab_1: true,
    goods: {
      goods_pic: '',
    },
    refund_data_1: {},
    refund_data_2: {},
    unit: '',
    imgUrl: app.imgUrl,
    isFocus: false,
  },

  onLoad(options) {
    let opts = options || {};
    let entry = opts.entry || '';
    let that = this;
    app.pageOnLoad(that);
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    that.setData({
      opts,
    });
    if (entry) {
      let previewUrl = '';
      let submitUrl = '';
      let backUrl = '/ws_micro_shop/pages/order/order';
      if (entry === 'default') {
        previewUrl = api.order.refund_preview;
        submitUrl = api.order.refund;
      } else if (entry === 'ms') {
        previewUrl = api.miaosha.refund_preview;
        submitUrl = api.miaosha.refund;
      } else if (entry === 'pt') {
        previewUrl = api.group.order.refund_preview;
        submitUrl = api.group.order.refund;
      }
      app.ws_micro_shoprequest({
        url: previewUrl,
        data: {
          order_detail_id: opts.id,
        },
        success: function(res) {
          if (res.code === 0) {
            that.setData({
              goods: res.data,
              money: res.data.item_pay_price,
              max_refund_price: res.data.max_refund_price,
              moneyNum: res.data.item_pay_price,
            });
          }
          if (res.code === 1) {
            wx.showModal({
              title: '提示',
              content: res.msg,
              showCancel: false,
              success: function(res) {
                if (res.confirm) {
                  wx.navigateBack();
                }
              },
            });
          }
        },
      });
      that.setData({
        previewUrl,
        submitUrl,
        backUrl,
      });
    } else {
      app.util.navigateTo('/ws_micro_shop/pages/user/user');
    }
  },

  switchTab(e) {
    let id = Number(e.currentTarget.dataset.id);
    if (id === 1) {
      this.setData({
        switch_tab_1: true,
      });
    } else {
      this.setData({
        switch_tab_1: false,
      });
    }
  },

  getRefundPrice(e) {
    let { value } = e.detail;
    
    this.setData({
      money: value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'),
      moneyNum: value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'),
    })
  },
  changeprice() {
    this.setData({
      money: '',
      isFocus: true,
    })
  },

  getRealPrice() {
    this.setData({
      money: this.data.moneyNum,
      isFocus: false,
    })
  },

  descInput(e) {
    let type = Number(e.currentTarget.dataset.type);
    let value = e.detail.value;
    if (type === 1) {
      let refund_data_1 = this.data.refund_data_1;
      refund_data_1.desc = value;
      this.setData({
        refund_data_1,
      });
    }
    if (type === 2) {
      let refund_data_2 = this.data.refund_data_2;
      refund_data_2.desc = value;
      this.setData({
        refund_data_2,
      });
    }
  },

  chooseImage(e) {
    let that = this;
    let type = Number(e.currentTarget.dataset.type);
    let max_pic_num = 6;
    let pic_num;
    let _count;
    if (type === 1) {
      let refund_data_1 = that.data.refund_data_1;
      pic_num = 0;
      if (refund_data_1.pic_list) {
        pic_num = refund_data_1.pic_list.length || 0;
      }
      _count = max_pic_num - pic_num;
      wx.chooseImage({
        count: _count,
        success: function(res) {
          if (!refund_data_1.pic_list) {
            refund_data_1.pic_list = [];
          }
          refund_data_1.pic_list = refund_data_1.pic_list.concat(
            res.tempFilePaths
          );
          that.setData({
            refund_data_1,
          });
        },
      });
    }
    if (type === 2) {
      let refund_data_2 = that.data.refund_data_2;
      pic_num = 0;
      if (refund_data_2.pic_list) {
        pic_num = refund_data_2.pic_list.length || 0;
      }
      _count = max_pic_num - pic_num;
      wx.chooseImage({
        count: _count,
        success: function(res) {
          if (!refund_data_2.pic_list) {
            refund_data_2.pic_list = [];
          }
          refund_data_2.pic_list = refund_data_2.pic_list.concat(
            res.tempFilePaths
          );
          that.setData({
            refund_data_2,
          });
        },
      });
    }
  },

  deleteImage(e) {
    let type = Number(e.currentTarget.dataset.type);
    let index = e.currentTarget.dataset.index;
    if (type === 1) {
      let refund_data_1 = this.data.refund_data_1;
      refund_data_1.pic_list.splice(index, 1);
      this.setData({
        refund_data_1,
      });
    }
    if (type === 2) {
      let refund_data_2 = this.data.refund_data_2;
      refund_data_2.pic_list.splice(index, 1);
      this.setData({
        refund_data_2,
      });
    }
  },

  refundSubmit(e) {
    let that = this;
    let type = Number(e.currentTarget.dataset.type);
    let url = 'utility/file/upload';
    if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
      url = app.util.url(url, { type: 'image', thumb: '0' });
    }
    if (type === 1) {
      let desc = that.data.refund_data_1.desc || '';
      if (desc.length === 0) {
        wx.showToast({
          title: '请填写退款原因',
          icon: 'none',
        });
        return;
      }
      let { max_refund_price, money } = this.data;
      if (Number(money) > Number(max_refund_price)) {
        wx.showToast({
          title: '最大可申请退款￥' + max_refund_price,
          icon: 'none'
        })
        return;
      }
      let pic_url_list = [];
      let pic_complete_count = 0;
      let picList = that.data.refund_data_1.pic_list;
      let uploadFunc = i => {
        wx.uploadFile({
          url,
          filePath: picList[i],
          name: 'file',
          formData: {
            _acid: app.siteInfo.acid,
            _uniacid: app.siteInfo.uniacid,
          },
          complete: function(res) {
            let _res = JSON.parse(res.data);
            pic_complete_count++;
            if (_res && _res.url) {
              pic_url_list[i] = _res.url;
            } else {
              wx.showToast({
                title: _res.error.message + ',已被过滤' || '上传失败',
                icon: 'none',
              });
            }
            if (pic_complete_count === picList.length) {
              wx.hideLoading();
              _submit();
            }
          },
        });
      };
      let _submit = () => {
        wx.showLoading({
          title: '正在提交',
          mask: true,
        });
        app.ws_micro_shoprequest({
          url: that.data.submitUrl,
          method: 'POST',
          data: {
            type: 1,
            order_detail_id: that.data.goods.order_detail_id,
            desc: desc,
            pic_list: JSON.stringify(pic_url_list),
            refund_price: money
          },
          success: function(res) {
            wx.hideLoading();
            if (res.code === 0) {
              wx.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
                success: function(res) {
                  if (res.confirm) {
                    app.util.navigateTo(
                      that.data.backUrl,
                      { status: 4 },
                      true
                    );
                  }
                },
              });
            }
            if (res.code === 1) {
              wx.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
                success: function(res) {
                  if (res.confirm) {
                    // wx.navigateBack({
                    //   delta: 1,
                    // });
                  }
                },
              });
            }
          },
        });
      };
      if (picList && picList.length > 0) {
        wx.showLoading({
          title: '正在上传图片',
          mask: true,
        });
        for (let i in picList) {
          if (Object.prototype.hasOwnProperty.call(picList, i)) {
            uploadFunc(i);
          }
        }
      } else {
        _submit();
      }
    }
    if (type === 2) {
      let desc = that.data.refund_data_2.desc || '';
      if (desc.length === 0) {
        wx.showToast({
          title: '请填写换货说明',
          icon: 'none',
        });
        return;
      }
      let pic_url_list = [];
      let pic_complete_count = 0;
      let picList = that.data.refund_data_2.pic_list;
      let uploadFunc = i => {
        wx.uploadFile({
          url,
          filePath: picList[i],
          name: 'file',
          formData: {
            _acid: app.siteInfo.acid,
            _uniacid: app.siteInfo.uniacid,
          },
          complete: function(res) {
            let _res = JSON.parse(res.data);
            pic_complete_count++;
            if (_res && _res.url) {
              pic_url_list[i] = _res.url;
            } else {
              wx.showToast({
                title: _res.error.message + ',已被过滤' || '上传失败',
                icon: 'none',
              });
            }
            if (pic_complete_count === picList.length) {
              wx.hideLoading();
              _submit();
            }
          },
        });
      };
      let _submit = () => {
        wx.showLoading({
          title: '正在提交',
          mask: true,
        });
        app.ws_micro_shoprequest({
          url: that.data.submitUrl,
          method: 'POST',
          data: {
            type: 2,
            order_detail_id: that.data.goods.order_detail_id,
            desc: desc,
            pic_list: JSON.stringify(pic_url_list),
          },
          success: function(res) {
            wx.hideLoading();
            if (res.code === 0) {
              wx.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
                success: function(res) {
                  if (res.confirm) {
                    app.util.navigateTo(
                      that.data.backUrl,
                      { status: 4 },
                      true
                    );
                  }
                },
              });
            }
            if (res.code === 1) {
              wx.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
                success: function(res) {
                  if (res.confirm) {
                    wx.navigateBack({
                      delta: 1,
                    });
                  }
                },
              });
            }
          },
        });
      };
      if (picList && picList.length > 0) {
        wx.showLoading({
          title: '正在上传图片',
          mask: true,
        });
        for (let i in picList) {
          if (Object.prototype.hasOwnProperty.call(picList, i)) {
            uploadFunc(i);
          }
        }
      } else {
        _submit();
      }
    }
  },

  collectFormId(e) {
    app.collectFormId(e);
  },
});
